#include <iostream>
#include <pthread.h>
#include <string>
#include <cassert>
#include <unistd.h>
#include "Thread.hpp"
#include "Mutex.hpp"

int tickets = 1000;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *thread_run(void *args)
{
    std::string work_type = static_cast<const char *>(args);
    while (1)
    {
        {
            LockGuard lockguard(&lock); // RAII风格的加锁
            // 传入lock，在初始化列表自动构造Mutex对象，在LockGuard的构造函数体内自动调用Mutex::lock()完成加锁

            // pthread_mutex_lock(&lock);
            if (tickets > 0)
            {
                usleep(1000);
                std::cout << work_type << " " << tickets-- << std::endl;

                // pthread_mutex_unlock(&lock);
            }
            else
            {
                // pthread_mutex_unlock(&lock);
                break;
            }
        }
        usleep(100); // 抢完票干其他事情
    }
}

int main()
{
    std::unique_ptr<Thread> thread1(new Thread(thread_run, (void *)"user1", 1));
    std::unique_ptr<Thread> thread2(new Thread(thread_run, (void *)"user2", 2));
    std::unique_ptr<Thread> thread3(new Thread(thread_run, (void *)"user3", 3));
    std::unique_ptr<Thread> thread4(new Thread(thread_run, (void *)"user4", 4));

    thread1->join();
    thread2->join();
    thread3->join();
    thread4->join();

    return 0;
}